package city.spring.modules.personnel.controller;

import city.spring.modules.ext.entity.TrainEmployeeExt;
import city.spring.modules.ext.service.TrainEmployeeExtService;
import city.spring.modules.personnel.entity.EmployeeEntity;
import city.spring.modules.personnel.entity.EmployeeTrainingEntity;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.modules.personnel.service.EmployeeTrainingService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller：培训/员工联系
 *
 * @author pxm
 * @date 2020-06-18 15:00:53
 */
@RestController
@RequestMapping("/train_employee_ext")
public class TrainEmployeeExtController extends ApiController {
    private final TrainEmployeeExtService trainEmployeeExtService;
    private final EmployeeService employeeService;
    private final EmployeeTrainingService employeeTrainingService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<TrainEmployeeExt, ?>> entityOrderFields;

    public TrainEmployeeExtController(TrainEmployeeExtService trainEmployeeExtService, EmployeeController employeeController, EmployeeService employeeService, EmployeeTrainingService employeeTrainingService) {
        this.trainEmployeeExtService = trainEmployeeExtService;
        this.employeeService = employeeService;
        this.employeeTrainingService = employeeTrainingService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(TrainEmployeeExt::getId);
        entityOrderFields.add(TrainEmployeeExt::getTrainId);
        entityOrderFields.add(TrainEmployeeExt::getRelatedId);
    }

    /**
     * 获取全部的 <strong>培训/员工联系</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, TrainEmployeeExt entity) {
        LambdaQueryChainWrapper<TrainEmployeeExt> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>培训/员工联系</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, TrainEmployeeExt entity) {
        LambdaQueryChainWrapper<TrainEmployeeExt> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<TrainEmployeeExt> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        for (TrainEmployeeExt record : page.getRecords()) {
            try {
                EmployeeEntity employeeEntity = employeeService.getById(record.getRelatedId());
                record.setPersonName(employeeEntity.getName());
            } catch (Exception ignore) {
                record.setRelatedId(null);
                record.setPersonName("< 找不到员工 >");
            }
            try {
                EmployeeTrainingEntity employeeTrainingEntity = employeeTrainingService.getById(record.getTrainId());
                record.setTrainName(employeeTrainingEntity.getName());
                // 培训开始时间
                record.setTrainStart(employeeTrainingEntity.getStart());
                // 培训结束时间
                record.setTrainEnd(employeeTrainingEntity.getEnd());
                // 培训时长，两个日期相差分钟数
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String endTime = df.format(employeeTrainingEntity.getEnd());
                String startTime = df.format(employeeTrainingEntity.getStart());
                long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                long nh = 1000 * 60 * 60;// 一小时的毫秒数
                long nm = 1000 * 60;// 一分钟的毫秒数
                long diff = df.parse(endTime).getTime() - df.parse(startTime).getTime(); // 两个日期毫秒差异
                long minutes = diff / nm;
                record.setTrainLength(minutes);
            } catch (Exception ignore) {
                record.setTrainId(null);
                record.setTrainName("< 找不到培训 >");
            }
        }
        return success(page);
    }


    /**
     * 删除一个 <strong>培训-员工联系</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        trainEmployeeExtService.deleteTrainEmployeeExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>培训-员工联系</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        trainEmployeeExtService.deleteTrainEmployeeExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<TrainEmployeeExt> buildLambdaQuery(TrainEmployeeExt entity) {
        LambdaQueryChainWrapper<TrainEmployeeExt> lambdaQuery = trainEmployeeExtService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, TrainEmployeeExt::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTrainId()), TrainEmployeeExt::getTrainId, entity.getTrainId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRelatedId()), TrainEmployeeExt::getRelatedId, entity.getRelatedId());
        return lambdaQuery;
    }

}
